package thread;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class RaceCallable  {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        FutureTask<String> futureTask = new FutureTask<String>(new RabbitAndTurtleCallable());
        new Thread(futureTask,"乌龟").start();

        FutureTask<String> futureTask1 = new FutureTask<String>(new RabbitAndTurtleCallable());
        new Thread(futureTask1,"兔子").start();

        System.out.println(futureTask.get());
        System.out.println(futureTask1.get());


    }
}

class RabbitAndTurtleCallable implements Callable<String>{

    private int length = 100;

    private int prelenth = 0;

    private static volatile boolean flag = true;
    @Override
    public String call() throws Exception {

        while (flag){
            Thread.sleep(100);
            if (Thread.currentThread().getName().equals("乌龟")){
                prelenth++;
                System.out.println(Thread.currentThread().getName()+"跑了"+prelenth+"米");
                if (prelenth==length){
                    flag = false;
                    return Thread.currentThread().getName()+"赢了了";
                }
            }
            Thread.sleep(100);
            if (Thread.currentThread().getName().equals("兔子")){
                prelenth = prelenth +2;
                System.out.println(Thread.currentThread().getName()+"跑了"+prelenth+"米");
                if (prelenth>=60){
                    System.out.println("兔子领先太多，需要睡觉....");
                    Thread.sleep(20*1000);
                }
                if (prelenth==length){
                    flag = false;
                    return Thread.currentThread().getName()+"赢了了";
                }
            }
        }
        return Thread.currentThread().getName()+"跑输了";
    }
}


